package com.jeanbart.factory.api.apiImpl;

import com.jeanbart.bean.Player;
import com.jeanbart.factory.api.wowsAPI;
import com.jeanbart.util.AgetB;
import com.jeanbart.util.WowsHttpRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;


public class apiWG implements wowsAPI, Callable {

    private Player player = null;
    private List<Player> playerList = null;
    private String UidRequestUrl = "";
    private String RateRequestUrl = "";
    private String ShipRateRequestUrl = "";
    public apiWG(Player player,String service){
        this.player = player;
        this.setUrl(service);
    }
    public apiWG(List<Player> playerList,String service){
        this.playerList = playerList;
        this.setUrl(service);
    }

    @Override
    public Object call() throws Exception {
        if(this.playerList!=null){
            switch(playerList.get(0).getStep()){
                case 1: getUids(playerList);//这一步不break
                case 2: PlayerInfos(playerList);break;
            }
        }else{
            getShipRate(player);
        }
        return 1;
    }
    //获取account_id
    public void getUids(List<Player> playerList) {
        AgetB get = new AgetB();
        String names = get.playerListGetNames(playerList);
        String requestUrl = this.UidRequestUrl;
        //params用于存储要请求的参数
        Map params = new HashMap();
        //showapi_appid的值，把###替换成你的appid
        //我们请求的字符串
        params.put("search",names);
        params.put("type","exact");
        //数字签名，###填你的数字签名，可以在你的个人中心看到
        //params.put("showapi_sign","###");
        //调用httpRequest方法，这个方法主要用于请求地址，并加上请求参数
        String string = new WowsHttpRequest().httpRequest(requestUrl,params);
        //处理返回的JSON数据并返回
        JSONArray ja= JSONObject.fromObject(string).getJSONArray("data");
        for(int i=0;i<ja.size();i++){
            String name = ja.getJSONObject(i).getString("nickname");
            String uid = ja.getJSONObject(i).getString("account_id");
            for(int j=0;j<playerList.size();j++) {
                if(playerList.get(j).getAccountName().equals(name)) {
                    playerList.get(j).setUid(uid);
                    break;
                }
            }
        }
    }

    //根据account_id获取胜率等信息
    public void PlayerInfos(List<Player> playerList) {
        AgetB get = new AgetB();
        String uids = get.playerListGetUids(playerList);

        String requestUrl = this.RateRequestUrl;
        Map params = new HashMap();
        params.put("account_id",uids);
        params.put("fields","statistics.pvp.battles,statistics.pvp.wins,nickname");
        String string = new WowsHttpRequest().httpRequest(requestUrl,params);
        JSONObject jo= JSONObject.fromObject(string).getJSONObject("data");
        for(String Uid:uids.split(",")){
            for(int i=0;i<playerList.size();i++) {
                if(playerList.get(i).getUid().equals(Uid)) {
                    playerList.get(i).Update(get.JSONObjectGetPlayer(jo.getJSONObject(Uid)));
                    break;
                }
            }
        }
    }

    /*@Override
    public void getShipRate(Player player) {
        String Uid = player.getUid();
        String ShipId = player.getShipId();
        String requestUrl = this.ShipRateRequestUrl;

        Map params = new HashMap();
        params.put("account_id",Uid);
        params.put("ship_id",ShipId);
        params.put("fields","pvp.battles,pvp.wins");
        String string = new WowsHttpRequest().httpRequest(requestUrl,params);
        JSONObject ratejo= JSONObject.fromObject(string);
        double rate=-1;
        if(true||"ok".equals(ratejo.getString("status"))&&Uid.equals(ratejo.getJSONObject("meta").getString("hidden"))){ //看有没有锁战绩
            //wg的接口出了些问题，有船玩，但是搜索不到，这时get(uid)是null，不是jsonarray
            try {
                ratejo = ratejo.getJSONObject("data").getJSONArray(Uid).getJSONObject(0).getJSONObject("pvp");
                player.setShipCount("" + ratejo.getInt("battles"));
                player.setShipWinCount("" + ratejo.getInt("wins"));
                if(ratejo.getInt("battles")!=0) {
                    rate = 1.0 * ratejo.getInt("wins")
                            / ratejo.getInt("battles");
                    player.setShipRate(rate);
                }else{
                    player.setShipRate(-1);
                }
            }catch (Exception e){
                player.setShipCount("-1");
                player.setShipWinCount("-1");
                player.setShipRate(0);
            }
        }
        else{
            player.setShipCount("-1");
            player.setShipWinCount("-1");
            player.setShipRate(0);
        }
    }*/

    @Override
    public void getShipRate(Player player) {
        Double Rate = player.getRate();
        String shipId = player.getShipId();
        //隐藏战绩的
        if(Rate==-1){
            player.setShipCount("-1");
            player.setShipWinCount("-1");
            player.setShipRate(-1);//去掉自带的百分号
            return;
        }
        String playerURL = this.ShipRateRequestUrl+player.getUid()+"/";
        URL url= null;
        try {
            url = new URL(playerURL);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.addRequestProperty("X-Requested-With","XMLHttpRequest");
        InputStream in = null;
        try {
            in = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long startTime = System.currentTimeMillis();
        String html = new BufferedReader(new InputStreamReader(in)).lines()
                .parallel().collect(Collectors.joining(System.lineSeparator()));
        long endTime = System.currentTimeMillis();
        //System.out.println("下载时间="+(endTime-startTime)+"ms");
        Document doc= Jsoup.parse(html);
        Elements e=doc.select("tr[ref^=\""+shipId+"\"]");
        player.setShipCount(e.select("tbody > tr:nth-child(1) ._value>span").first().text());
        player.setShipWinCount(e.select("tbody > tr:nth-child(2) ._value>span").first().text());
        if(!Double.valueOf(player.getShipCount()).equals(0)) {
            Double rate = Double.valueOf(player.getShipWinCount()) / Double.valueOf(player.getShipCount());
            player.setShipRate(rate);
        }else{
            player.setShipRate(0);
        }
    }

    @Deprecated
    @Override
    public void getUid(Player player) {
        String name = player.getAccountName();
        String Uid="";
        String requestUrl = this.UidRequestUrl;
        Map params = new HashMap();
        params.put("search",name);
        params.put("type","exact");
        String string = new WowsHttpRequest().httpRequest(requestUrl,params);
        Uid= JSONObject.fromObject(string).getJSONArray("data").getJSONObject(0).getString("account_id");
    }

    @Deprecated
    @Override
    public void PlayerInfo(Player player) {
        String name = player.getAccountName();
        String Uid = player.getUid();
        String requestUrl = this.RateRequestUrl;
        Map params = new HashMap();
        params.put("account_id",Uid);
        params.put("fields","statistics.pvp.battles,statistics.pvp.wins,nickname");
        String string = new WowsHttpRequest().httpRequest(requestUrl,params);
        JSONObject ratejo= JSONObject.fromObject(string).getJSONObject("data").getJSONObject(Uid);
        double rate=-1;
        player.setUid(Uid);
        player.setAccountName(name);
        if(ratejo.getString("statistics")!="null"){ //看有没有锁战绩
            player.setCount(ratejo.getJSONObject("statistics").getJSONObject("pvp").getString("battles"));
            rate=1.0*ratejo.getJSONObject("statistics").getJSONObject("pvp").getInt("wins")
                    /ratejo.getJSONObject("statistics").getJSONObject("pvp").getInt("battles");
            player.setRate(rate);
        }
        else{
            player.setCount(""+-1);
            rate=-1;
            player.setRate(rate);
        }
    }

    public void setUrl(String service){
        String UidRequestUrlru="https://api.worldofwarships.ru/wows/account/list/";
        String UidRequestUrleu="https://api.worldofwarships.eu/wows/account/list/";
        String UidRequestUrlna="https://api.worldofwarships.com/wows/account/list/";
        String UidRequestUrlasia="https://api.worldofwarships.asia/wows/account/list/";

        String RateRequestUrlru="https://api.worldofwarships.ru/wows/account/info/";
        String RateRequestUrleu="https://api.worldofwarships.eu/wows/account/info/";
        String RateRequestUrlna="https://api.worldofwarships.com/wows/account/info/";
        String RateRequestUrlasia="https://api.worldofwarships.asia/wows/account/info/";

        /*String ShipRateRequestUrlru="https://api.worldofwarships.ru/wows/ships/stats/";
        String ShipRateRequestUrleu="https://api.worldofwarships.ru/wows/ships/stats/";
        String ShipRateRequestUrlna="https://api.worldofwarships.eu/wows/ships/stats/";
        String ShipRateRequestUrlasia="https://api.worldofwarships.asia/wows/ships/stats/";*/
        String ShipRateRequestUrlru="https://worldofwarships.ru/zh-tw/community/accounts/tab/pvp/ships/";
        String ShipRateRequestUrleu="https://worldofwarships.eu/zh-tw/community/accounts/tab/pvp/ships/";
        String ShipRateRequestUrlna="https://worldofwarships.com/zh-tw/community/accounts/tab/pvp/ships/";
        String ShipRateRequestUrlasia="https://worldofwarships.asia/zh-tw/community/accounts/tab/pvp/ships/";
        if(service.equals("RU")){
            this.UidRequestUrl = UidRequestUrlru;
            this.RateRequestUrl = RateRequestUrlru;
            this.ShipRateRequestUrl = ShipRateRequestUrlru;
        }else if(service.equals("EU")){
            this.UidRequestUrl = UidRequestUrleu;
            this.RateRequestUrl = RateRequestUrleu;
            this.ShipRateRequestUrl = ShipRateRequestUrleu;
        }else if(service.equals("COM")){
            this.UidRequestUrl = UidRequestUrlna;
            this.RateRequestUrl = RateRequestUrlna;
            this.ShipRateRequestUrl = ShipRateRequestUrlna;
        }else if(service.equals("ASIA")){
            this.UidRequestUrl = UidRequestUrlasia;
            this.RateRequestUrl = RateRequestUrlasia;
            this.ShipRateRequestUrl = ShipRateRequestUrlasia;
        }
    }
}
